#include<unordered_map>
#include<vector>
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    std::unordered_map<int,int> im ;
    TreeNode* buildTree(std::vector<int>& preorder,std::vector<int>& inorder) {
    int n =  inorder.size();
        for (int i = 0; i < n; i++)
        {
            im.insert({inorder[i],i}); 
        }
        return build(preorder,0,n-1,inorder,0,n-1);
    }
TreeNode * build(const std::vector<int>& preorder, int l1,int r1,const std::vector<int>& inorder,int l2,int r2)
    {
        if (l1>r1) return nullptr;
        if (l1==r1) return new TreeNode(preorder[l1]);
        TreeNode* root =new TreeNode(preorder[l1]);
        int len = im[preorder[l1]] -l2;
        root->left = build(preorder,l1+1,l1+len,inorder,l2,im[preorder[l1]]-1);
        root->right = build(preorder,l1+len+1,r1,inorder,im[preorder[l1]]+1,r2);
        return root;
    }
    
};
